package com.dream21th.admin.utils;

import lombok.extern.slf4j.Slf4j;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Random;

@Slf4j
public class AESUtils {

    public static String getCharAndNum(int length) {
        StringBuffer buffer = new StringBuffer();
        Random random = new Random();

        for (int i = 0; i < length; ++i) {
            if (random.nextInt(2) % 2 == 0) {
                int choice = 97;
                buffer.append((char) (choice + random.nextInt(26)));
            } else {
                buffer.append(String.valueOf(random.nextInt(10)));
            }
        }
        return buffer.toString();
    }

    public static String encrypt(String sKey, String src) throws Exception {

        byte[] raw = sKey.getBytes("utf-8");
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//"算法/模式/补码方式"
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(src.getBytes("utf-8"));
        return Base64.getEncoder().encodeToString(encrypted);
    }

    public static String decrypt(String sKey, String src) throws Exception {
        try {
            byte[] raw = sKey.getBytes("utf-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            byte[] encrypted1 = Base64.getDecoder().decode(src);//先用base64解密
            byte[] original = cipher.doFinal(encrypted1);
            return new String(original, "utf-8");
        } catch (Exception e) {
            log.error("解密错误", e);
            throw new RuntimeException("解密错误");
        }
    }
}
